package com.qiguliuxing.dts.wx.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.common.constant.ApiAdminConsts;
import com.qiguliuxing.dts.common.constant.LogParamsConsts;
import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.core.annotation.LoginUser;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import com.qiguliuxing.dts.db.bean.CommentInfo;
import com.qiguliuxing.dts.db.domain.DtsComment;
import com.qiguliuxing.dts.service.base.DtsCommentService;
import com.qiguliuxing.dts.service.base.DtsGoodsService;
import com.qiguliuxing.dts.service.base.DtsTopicService;
import com.qiguliuxing.dts.service.base.DtsUserService;
import com.qiguliuxing.dts.wx.service.UserInfoService;
import com.qiguliuxing.dts.wx.vo.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户评论服务
 */
@RestController
@RequestMapping("/wx/comment")
@Validated
@Api(tags = "用户评论服务")
public class WxCommentController {
	private static final Logger logger = LoggerFactory.getLogger(WxCollectController.class);

	@Autowired
	private DtsCommentService commentService;
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private DtsGoodsService goodsService;
	@Autowired
	private DtsTopicService topicService;

	@Autowired
	private DtsUserService dtsUserService;


	private Object validate(DtsComment comment) {
		String content = comment.getContent();
		if (StringUtils.isEmpty(content)) {
			return ResponseUtils.badArgument();
		}
		if(null==comment.getGoodsId()){
			return ResponseUtils.badArgument();
		}

		Short star = comment.getStar();
		if (star == null) {
			return ResponseUtils.badArgument();
		}
		if (star < 0 || star > 5) {
			return ResponseUtils.badArgumentValue();
		}

		Byte type = comment.getType();
		Integer valueId = comment.getValueId();
		if (type == null || valueId == null) {
			return ResponseUtils.badArgument();
		}
		if (type == 0) {
			if (goodsService.findById(valueId) == null) {
				return ResponseUtils.badArgumentValue();
			}
		} else if (type == 1) {
			if (topicService.findById(valueId) == null) {
				return ResponseUtils.badArgumentValue();
			}
		} else {
			return ResponseUtils.badArgumentValue();
		}
		return null;
	}

	/**
	 * 发表评论
	 *
	 * @param userId
	 *            用户ID
	 * @param comment
	 *            评论内容
	 * @return 发表评论操作结果
	 */
	@PostMapping("post")
	@ApiOperation(value = "发表评论")
	@WebLog(description = "发表评论")
	public Object post(@LoginUser Integer userId, @RequestBody DtsComment comment) {
		if (userId == null) {
			logger.error("用户发表评论失败:用户未登录！！！");
			return ResponseUtils.unlogin();
		}
		Object error = validate(comment);
		if (error != null) {
			return error;
		}
		comment.setIsSelected(false);
		comment.setUserId(userId);
		try {
			comment.setIsRoot(true);
			commentService.save(comment);
		} catch (Exception e) {
			logger.error("用户发表评论失败:存储评论数据到库出错！");
			e.printStackTrace();
		}
		return ResponseUtils.ok(comment);
	}

	/**
	 * 评论数量
	 *
	 * @param type
	 *            类型ID。 如果是0，则查询商品评论；如果是1，则查询专题评论。
	 * @param valueId
	 *            商品或专题ID。如果type是0，则是商品ID；如果type是1，则是专题ID。
	 * @return 评论数量
	 */
	@GetMapping("count")
	@ApiOperation(value = "评论数量")
	@WebLog(description = "评论数量")
	public Object count(@ApiParam(value = "类型ID。如果是0，则查询商品评论；如果是1，则查询专题评论。") @NotNull Byte type,
						@ApiParam(value = "商品或专题ID。如果type是0，则是商品ID；如果type是1，则是专题ID。") @NotNull Integer valueId) {
		int allCount = commentService.count(type, valueId, 0);
		int hasPicCount = commentService.count(type, valueId, 1);
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("allCount", allCount);
		data.put("hasPicCount", hasPicCount);
		return ResponseUtils.ok(data);
	}

	/**
	 * 评论列表
	 *
	 * @param type
	 *            类型ID。 如果是0，则查询商品评论；如果是1，则查询专题评论。
	 * @param valueId
	 *            商品或专题ID。如果type是0，则是商品ID；如果type是1，则是专题ID。
	 * @param showType
	 *            显示类型。如果是0，则查询全部；如果是1，则查询有图片的评论。
	 * @param page
	 *            分页页数
	 * @param size
	 *            分页大小
	 * @return 评论列表
	 */
	@GetMapping("list")
	@ApiOperation(value = "评论列表")
	@WebLog(description = "评论列表",excludes = {LogParamsConsts.RESPONSE})
	public Object list(@ApiParam(value = "类型ID。 如果是0，则查询商品评论；如果是1，则查询专题评论。") @NotNull Byte type,
					   @ApiParam(value = "商品或专题ID。如果type是0，则是商品ID；如果type是1，则是专题ID。") @NotNull Integer valueId,
					   @ApiParam(value = "显示类型。如果是0，则查询全部；如果是1，则查询有图片的评论") @NotNull Integer showType,
					   @ApiParam(value = "页码",defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
					   @ApiParam(value = "分页大小",defaultValue = "10") @RequestParam(defaultValue = "10") Integer size) {
		List<DtsComment> commentList = commentService.query(type, valueId, showType, page, size);

		long count = PageInfo.of(commentList).getTotal();
		List<Map<String, Object>> commentVoList = new ArrayList<>(commentList.size());
		for (DtsComment comment : commentList) {
			Map<String, Object> commentVo = new HashMap<>();
			commentVo.put("addTime", comment.getAddTime());
			commentVo.put("content", comment.getContent());
			commentVo.put("picList", comment.getPicUrls());
			commentVo.put("star",comment.getStar());

			UserInfo userInfo = userInfoService.getInfo(comment.getUserId());
			commentVo.put("userInfo", userInfo);
			List<Map<String, Object>> replyList =  commentService.queryReply(comment.getId(), comment.getValueId());
			commentVo.put("reply", replyList);

			commentVoList.add(commentVo);
		}

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("data", commentVoList);
		data.put("count", count);
		data.put("currentPage", page);
		return ResponseUtils.ok(data);
	}
	@GetMapping("lists")
	@ApiOperation(value = "评论列表")
	@WebLog(description = "评论列表",excludes = {LogParamsConsts.RESPONSE})
	public Object list(
			@ApiParam(value = "用户昵称") String nickname,
			@ApiParam(value = "商品编号") String goodsSn,
			@ApiParam(value = "商品名称") String goodsName,
			@ApiParam(value = "页码",defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
			@ApiParam(value = "分页大小",defaultValue = "10") @RequestParam(defaultValue = "10") Integer limit,
			@ApiParam(value = "排序字段",defaultValue = "add_time") @Sort @RequestParam(defaultValue = "add_time") String sort,
			@ApiParam(value = "排序规则",defaultValue = "desc") @Order @RequestParam(defaultValue = "desc") String order) {
		// 需要区分数据权限，如果属于品牌商管理员，则需要获取当前用户管理品牌店铺
		List<Integer> brandIds = null;
		List<CommentInfo> commentList = null;
		long total = 0L;
		commentList = commentService.queryBrandCommentSelective(brandIds, nickname,goodsName, goodsSn, page, limit, sort, order,true);
		if(!commentList.isEmpty()){
			for(CommentInfo commentInfo:commentList){
				commentInfo.setUserVo(dtsUserService.findUserVoById(commentInfo.getUserId()));
				commentInfo.setDtsGoods(goodsService.findById(commentInfo.getGoodsId()));
			}
		}
		total = PageInfo.of(commentList).getTotal();
		Map<String, Object> data = new HashMap<>();
		data.put("total", total);
		data.put("items", commentList);
		return ResponseUtils.ok(data);
	}
}
